#从Python SDK导入BOS配置管理模块以及安全认证模块
from baidubce.bce_client_configuration import BceClientConfiguration
from baidubce.auth.bce_credentials import BceCredentials
from baidubce.services.bos.bos_client import BosClient
from logs.bdyun import DB

class Bd_storage(object):
    def __init__(self):
        # 设置BosClient的Host，Access Key ID和Secret Access Key
        self.bos_host = "https://gz.bcebos.com"
        self.access_key_id = DB.ak
        self.secret_access_key = DB.sk
        self.bucket_name = '1999momo'

    def user_bucket(self,bucket_name,client):
        # 如下代码可以新建一个Bucket：
        if not client.does_bucket_exist(bucket_name):
            client.create_bucket(bucket_name)

    def up_image(self,file,img_name):
        # 创建BceClientConfiguration
        config = BceClientConfiguration(credentials=BceCredentials(self.access_key_id, self.secret_access_key), endpoint=self.bos_host)
        # 新建BosClient
        client = BosClient(config=config)
        self.user_bucket(self.bucket_name,client) #去判断是否有此bucket
        try:
            # 从字符串中上传的Object
            res = client.put_object_from_string(bucket=self.bucket_name, key=img_name, data=file)
        except Exception as f:
            return None
        else:
            result = res.__dict__
            if result['metadata']:
                url = f'https://{self.bucket_name}.gz.bcebos.com/{img_name}'
                return url



if __name__ == '__main__':
    bd = Bd_storage()
    with open('罗小黑.png', 'rb') as f:
        s = f.read()
        name = '罗小黑'
        bd.up_image(s,name)



